<template>
  <div class="anySignMiniCore">
    <div id="alert_dialog" class="alert_dialog" style="display: none;">
      <div class="alert_area">
        <div class="alert_text">签名偶发异常，请尝试重新签名。如果还是不行，请切换其它签名方式，并上报相关情况。</div>
        <div id="btnAlert" class="alert_btn">确 定</div>
      </div>
    </div>
    <div class="dialog" v-show="isPopupShow">
      <div class="md-example-popup md-example-popup-bottom">
        <center>
          <div width="100%" id="single_dialog" style=" display:none;">
            <div width="100%" style="display: none;">
              <p width="100%" id="anysign_title" style="padding-bottom: 20px;"></p>
              <div width="100%" style="position: relative;">
                <div
                  style="position: absolute; top:-10px; left: 30px; width: 100px; background: #fff; padding-left:20px; height:15px;">
                  <img style="float: left;" width="15px" height="15px" :src="biPng" align="absmiddle"> 手写签名
                </div>
                <div id="single_signImage" class="signImagecss" style="overflow: hidden;width: 100% !important;">
                </div>
              </div>
            </div>
            <div id="single_tmpcanvascss" class="single_tmpcanvascss">
              <div id="single_signTitle" :style="{'background-image': 'url('+meterPng+') !important'}"></div>
              <canvas id="single_anysignCanvas"></canvas>
            </div>
            <div id="btnContainerInner" class="btncontainer">
              <input type="button" id="btnOK" @click="signSubmit()" class="button_new" value="确 定">
              <input type="button" id="btnBack" class="button_new" value="后 退" @click="signBack()">
              <input type="button" id="btnCancel" @click="cancelSign()" class="button_new" value="取 消">
            </div>
          </div>
          <div id="dialog" style=" display:none;">
            <div id="anysign_title" style="color:#333333;" width="100%" height="10%">{{signObj.signatureConfig.title}}
            </div>
            <div id="container" onmousedown="return false;">
              <canvas id="anysignCanvas" width="1">
              </canvas>
            </div>
            <div id="single_scrollbar" style="text-align: center;  vertical-align:middle; " width="100%">
              <span id="single_scroll_text"> *滑动操作：</span>
              <input id="single_scrollbar_up" type="button" class="button orange" value="左移" />
              <input id="single_scrollbar_down" type="button" class="button orange" value="右移" />
            </div>
            <div id="btnContainerOuter" width="100%">
              <div id="btnContainerInner" style="text-align: center;   font-size:5pt;" width="100%">
                <input id="btnOK" type="button" class="button orange" value="确 定" @click="signSubmit()" />
                <input id="btnClear" type="button" class="button orange" value="清 屏"
                  onclick="javascript:clear_canvas();">
                <input id="btnCancel" type="button" class="button orange" value="取 消" @click="cancelSign()">
              </div>
            </div>
          </div>
          <div id="comment_dialog" style="display:none;">
            <div id="leftView" style="display:none;">
              <p id="comment_title"></p>
              <div id="signImage" class="signImagecss"></div>
            </div>
            <div id="tmpcanvascss" class="tmpcanvascss">
              <div id="signTitle"></div>
              <canvas id="comment_canvas"></canvas>
            </div>
            <div id="comment_btnContainerInner" class="comment_btncontainer">
              <input id="comment_ok" type="button" class="button orange" value="确 定" @click="signSubmit()">
              <input id="comment_back" type="button" class="button orange" value="后退" @click="commentBack()">
              <input id="comment_cancel" type="button" class="button orange" @click="commentCancel()" value="取 消">
            </div>
          </div>
        </center>
      </div>
    </div>
  </div>
</template>
<script>
  import {
    Toast,
    Popup
  } from 'mand-mobile'
  import http from '@/utils/http'
  export default {
    name: 'any-sign',
    components: {
      [Popup.name]: Popup,
    },
    props: {
      EncAlg: {
        type: String,
        default () {
          return 'SM2' //可选值RSA SM2
        }
      },
      channel: { //设置业务渠道号，渠道号应该为小于 20 位的数字，不能包含字母
        type: String,
      },
      formData: { //表单数据，类型为 base64 编码的 Utf8 字符串
        type: String,
        default () {
          return ''
        }
      },
      businessId: { //业务流水号，用于生成 pdf 的唯一标识，通常为集成信手书的业务系统中的业务流水号
        type: String,
        default () {
          return ''
        }
      },
      templateType: { //默认pdf,XML : 10,HTML : 11,PDF : 12,JSON : 13,PRESERVED : 19
        type: String,
        default () {
          return '12'
        }
      },
      /**
       * 后台签名所用的模板 id，只有 template_type 为 xml 的时候有
       效，其他情况可随意设置，需要在签名服务器添加配置信息，可向北京 CA 后台集成人员询
       问具体值
       */
      templateSerial: {
        type: String,
        default () {
          return ''
        }
      },
      contextId: {
        type: Array,
        default () {
          return [20]
        }
      },
      signObj: {
        type: Object,
        default () {
          return {
            signName: '',
            signIdNo: '',
            signLocaType: '', //1:关键字定位 2:坐标定位
            signRuleKeyWord: {
              keyword: '',
              xOffset: '',
              yOffset: '',
              pageNo: '',
              KWIndex: '',
            },
            signRuleXYZ: {
              left: '',
              top: '',
              right: '',
              bottom: '',
              pageNo: '',
              unit: ''
            },
            signatureConfig: {
              cid: '0',
              title: '请签名',
              titleSpanFromOffset: 4,
              titleSpanToOffset: 5,
              isTSS: false,
              nessesary: false,
              singleWidth: 50,
              singleHeight: 50,
              signature_stroke_width: 5, // 签名笔划粗细
              penColor: '#000000', // 签名字体颜色
              signatureImgRatio: '1.0', // 图片清晰度
              signature_max_times: 2, // ocr识别次数
              isdistinguish: true // 是否开启CA ocr识别
            },
            isOpenOcr: false,
            ocrObj: {
              iPAdress: '',
              businessNo: '',
              businessType: '',
              systemType: '',
            }
          }
        }
      },
      commentsObj: {
        type: Object,
        default () {
          return {
            signName: '',
            signIdNo: '',
            signLocaType: '', //1:关键字定位 2:坐标定位
            signRuleKeyWord: {
              keyword: '',
              xOffset: '',
              yOffset: '',
              pageNo: '',
              KWIndex: '',
            },
            signRuleXYZ: {
              left: '',
              top: '',
              right: '',
              bottom: '',
              pageNo: '',
              unit: ''
            },
            commentConfig: {
              cid: '30',
              commitment: '',
              commentImgRatio: 3.0, // 图片清晰度
              mass_words_in_single_line: 25,
              mass_word_height: 50,
              mass_word_width: 50,
              comment_stroke_width: 10, // 签名笔划粗细
              penColor: '#000000', // 签名字体颜色
              nessesary: false,
              comment_max_times: 2, // ocr识别次数
              isdistinguish: true, // 是否开启CA ocr识别
            },
            isOpenOcr: false,
            ocrObj: {
              iPAdress: '',
              businessNo: '',
              businessType: '',
              systemType: '',
            }
          }
        }
      }
    },
    data() {
      return {
        baseImges1: [],
        ocrCapture: null,
        biPng: 'https://cdn1.huaruisales.com/mobsite/lib/anysign_tp/image/bi.png',
        meterPng: 'https://cdn1.huaruisales.com/mobsite/lib/anysign_tp/image/meter.png',
        isPopupShow: false,
        apiInstance: null,
        signInfo: {},
        signImgs: [],
        commentImgs: [],
        resources: {
          css: {
            canvas_css: 'https://cdn1.huaruisales.com/mobsite/lib/anysign_tp/css/canvas_css.css',
            sp: 'https://cdn1.huaruisales.com/mobsite/lib/anysign_tp/css/sp.css',
            mw480Portrait: 'https://cdn1.huaruisales.com/mobsite/lib/anysign_tp/css/mw480Portrait.css',
            sw1024: 'https://cdn1.huaruisales.com/mobsite/lib/anysign_tp/css/sw1024.css'
          },
          js: {
            default: 'https://cdn1.huaruisales.com/mobsite/lib/anysign_tp/libs/zlib/deflate.min.js',
            cryptoCore: 'https://cdn1.huaruisales.com/mobsite/lib/anysign_tp/libs/CryptoJS v3.1.2/components/core-min.js',
            cryptoSha1: 'https://cdn1.huaruisales.com/mobsite/lib/anysign_tp/libs/CryptoJS v3.1.2/rollups/sha1.js',
            cryptoTripledes: 'https://cdn1.huaruisales.com/mobsite/lib/anysign_tp/libs/CryptoJS v3.1.2/rollups/tripledes.js',
            cryptoModeEcb: 'https://cdn1.huaruisales.com/mobsite/lib/anysign_tp/libs/CryptoJS v3.1.2/components/mode-ecb.js',
            anysignCommentUI: 'https://cdn1.huaruisales.com/mobsite/lib/anysign_tp/libs/anysignCommentUI.js',
            jquery: 'https://cdn1.huaruisales.com/mobsite/lib/anysign_tp/libs/jquery-1.4.2.min.js',
            anysignAll: 'https://cdn1.huaruisales.com/mobsite/lib/anysign_tp/libs/anysign_all.min_3.js',
            // anysignAll: 'https://cdn1.huaruisales.com/mobsite/lib/anysign_tp/libs/anysign_all.min3.0.2.js',
            // anysignAll: 'https://cdn1.huaruisales.com/mobsite/lib/anysign_tp/libs/anysign_all.min3.0.6.js',
            anysignWebInterface: 'https://cdn1.huaruisales.com/mobsite/lib/anysign_tp/anysignWebInterface.js',
          }
        }
      }
    },
    async created() {
      let _this = this
      if (typeof (window.anysignstartload) == 'undefined') {
        window.anysignstartload = true
        let cssObj = _this.resources.css
        let jsObj = _this.resources.js
        for (const key in _this.resources.css) {
          if (cssObj.hasOwnProperty(key)) {
            const cssUrl = cssObj[key]
            _this.initCss(cssUrl)
          }
        }
        await _this.initJs(jsObj.default) &&
          await _this.initJs(jsObj.cryptoCore) &&
          await _this.initJs(jsObj.cryptoSha1) &&
          await _this.initJs(jsObj.cryptoTripledes) &&
          await _this.initJs(jsObj.cryptoModeEcb) &&
          await _this.initJs(jsObj.anysignCommentUI) &&
          await _this.initJs(jsObj.jquery) &&
          await _this.initJs(jsObj.anysignAll) &&
          await _this.initJs(jsObj.anysignWebInterface) && (function () {
            window.loaded = true
            _this.initSign()
          }())
      }
    },
    methods: {
      initCss(url) {
        //初始化css
        let link = document.createElement('link')
        link.rel = 'icon'
        link.href = url
        document.body.appendChild(link)
      },
      async initJs(jsUrl) {
        return await new Promise((resolve) => {
          let script = document.createElement('script')
          let header = document.getElementsByTagName('head')[0]
          script.type = 'text/javascript'
          script.src = jsUrl
          header.appendChild(script)
          script.onload = script.onreadystatechange = function () {
            if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
              resolve(true)
            }
            script.onload.onload = script.onreadystatechange = null //删除事件处理函数。
          }
        })
      },
      initSign() {
        let _this = this
        window.custom_alert = function () {
          return
        }
        //识别回调接口
        let identify_callback = function (errCode) {
          console.log(errCode)
          if (errCode == '0') {
            return
          }
          if (errCode == '10003') {
            Toast.info('输入数据项无法解析！', 1000)
          } else if (errCode == '10011') {
            Toast.info('服务系统异常错误！', 1000)
          } else if (errCode == '10100') {
            Toast.info('识别结果为空！', 1000)
          } else if (errCode == '10101') {
            Toast.info('连接识别服务超时！', 1000)
          } else if (errCode == '10102') {
            Toast.info('连接识别服务异常！', 1000)
          } else if (errCode == '-1') {
            Toast.info('书写错误！', 1000)
          } else {
            Toast.info('签字识别失败，请稍后再试', 1000)
          }
        }
        let callback = function (context_id, context_type, val) {
          if (context_type == window.CALLBACK_TYPE_DIALOG_CANCEL ||
            context_type == window.CALLBACK_TYPE_START_RECORDING ||
            context_type == window.CALLBACK_TYPE_STOP_RECORDING) {
            return Toast.hide()
          }
          if (context_type == window.CALLBACK_TYPE_SIGNATURE) {
            //签名回显
            _this.signInfo.signImg = 'data:image/png;base64,' + val
          } else if (context_type == window.CALLBACK_TYPE_COMMENTSIGN) {
            //批注回显
            _this.signInfo.commentImg = 'data:image/png;base64,' + val
          }
          if (context_id == 20) {
            _this.$emit('signSubmit',
              context_id,
              _this.signInfo.signImg,
              Array.prototype.map.call(_this.signImgs, item => {
                return item.src
              })
            )
          }
          if (context_id == 21) {
            _this.signImgs = document.getElementById('single_signImage').querySelectorAll('img')
            if (_this.signImgs.length < _this.signObj.signName.length) {
              return Toast.info('请完成签名', 1000)
            }
            _this.$emit('signSubmit',
              context_id,
              _this.signInfo.signImg,
              Array.prototype.map.call(_this.signImgs, item => {
                return item.src
              })
            )
          } else if (context_id == 30) {
            _this.commentImgs = document.getElementById('signImage').querySelectorAll('img')
            if (_this.commentImgs.length < _this.commentsObj.commentConfig.commitment.length) {
              return Toast.info('请完成签名', 1000)
            }
            _this.$emit('signSubmit',
              context_id,
              _this.signInfo.commentImg,
              Array.prototype.map.call(_this.commentImgs, item => {
                return item.src
              })
            )
          }
          Toast.hide()
          _this.isPopupShow = false
        }
        window.EncAlgType.EncAlg = _this.EncAlg
        _this.apiInstance = new window.AnySignApi()
        //初始化签名接口
        let res = _this.apiInstance.initAnySignApi(callback, _this.channel)
        if (!res) {
          return Toast.info('初始化签名组件失败', 1000)
        }
        let ocrCapture = new window.OCRCapture();
        ocrCapture.text = "a";
        ocrCapture.IPAdress = process.env.VUE_APP_OCR_HWR
        ocrCapture.appID = "123";
        ocrCapture.count = 5;
        ocrCapture.language = Language.CHS;
        ocrCapture.resolution = 80;
        ocrCapture.serviceID = "999999";
        _this.ocrCapture = ocrCapture
        _this.setIdentifyCallBack(identify_callback)
        if (Array.isArray(_this.contextId)) {
          for (let i = 0; i < _this.contextId.length; i++) {
            const item = _this.contextId[i]
            res = item == 30 ? _this.addCommentObj(30) : _this.addSignatureObj(item)
            if (!res) {
              return Toast.info('初始化签名组件失败', 1000)
            }
          }
        }
        //将配置提交
        res = _this.apiInstance.commitConfig()

        if (!res) {
          return Toast.info('初始化签名组件失败', 1000)
        }
        _this.setTemplateData()
      },
      /**
       * 设置表单数据，每次业务都需要set一次
       * @param template_type 签名所用的模板类型
       * @param contentUtf8Str 表单数据，类型为Utf8字符串
       * @param businessId 业务工单号
       * @param templateSerial 模板序列号
       * @returns {*} 是否设置成功
       */
      setTemplateData() {
        //配置JSON格式签名原文
        let _this = this
        let res = _this.apiInstance.setTemplate(_this.templateType || window.TemplateType.PDF, _this.formData,
          _this.businessId, _this.templateSerial)
        if (res) {
          return console.log('设置模板数据成功')

        } else {
          console.log('设置模板数据失败')
          return Toast.info('设置模板数据失败', 1000)
        }
      },
      setIdentifyCallBack(callback) {
        if (!this.apiInstance) {
          console.log('信手书接口没有初始化')
          return Toast.info('信手书接口没有初始化', 1000)
        }
        this.apiInstance.setIdentifyCallBack(callback)
      },
      addSignatureObj(context_id) {
        let _this = this
        if (!_this.signObj.signName || !_this.signObj.signIdNo) {
          return false
        }
        let signer = new window.Signer(_this.signObj.signName, _this.signObj.signIdNo)
        let signerRule = null
        if (_this.signObj && _this.signObj.signLocaType == '1' && _this.signObj.signRuleKeyWord) {
          //关键字定位
          signerRule = new window.SignRule_KeyWordV2(_this.signObj.signRuleKeyWord.keyword,
            _this.signObj.signRuleKeyWord.xOffset,
            _this.signObj.signRuleKeyWord.yOffset,
            _this.signObj.signRuleKeyWord.pageNo,
            _this.signObj.signRuleKeyWord.KWIndex)
        } else if (_this.signObj && _this.signObj.signLocaType == '2' && _this.signObj.signRuleXYZ) {
          //坐标定位
          signerRule = new window.SignRule_XYZ(_this.signObj.signRuleXYZ.left,
            _this.signObj.signRuleXYZ.top,
            _this.signObj.signRuleXYZ.right,
            _this.signObj.signRuleXYZ.bottom,
            _this.signObj.signRuleXYZ.pageNo,
            _this.signObj.signRuleXYZ.unit)
        } else {
          return Toast.info('缺少定位参数', 1000)
        }
        let signatureConfig = new window.SignatureConfig(signer, signerRule)
        let timeTag = new window.TimeTag(1, 'yyyy-MM-dd hh:mm:ss')
        if (!_this.signObj.signatureConfig) {
          return Toast.info('缺少单签配置信息', 1000)
        }
        signatureConfig.cid = _this.signObj.signatureConfig.cid
        signatureConfig.title = _this.signObj.signatureConfig.title
        signatureConfig.titleSpanFromOffset = _this.signObj.signatureConfig.titleSpanFromOffset
        signatureConfig.titleSpanToOffset = _this.signObj.signatureConfig.titleSpanToOffset
        signatureConfig.isTSS = _this.signObj.signatureConfig.isTSS
        signatureConfig.nessesary = _this.signObj.signatureConfig.nessesary
        signatureConfig.singleWidth = _this.signObj.signatureConfig.singleWidth
        signatureConfig.singleHeight = _this.signObj.signatureConfig.singleHeight
        signatureConfig.signature_stroke_width = _this.signObj.signatureConfig.signature_stroke_width
        signatureConfig.penColor = _this.signObj.signatureConfig.penColor
        signatureConfig.signatureImgRatio = _this.signObj.signatureConfig.signatureImgRatio
        signatureConfig.timeTag = timeTag
        signatureConfig.signature_max_times = _this.signObj.signatureConfig.signature_max_times
        signatureConfig.isdistinguish = _this.signObj.signatureConfig.isdistinguish
        // let ocrCapture = null
        // if (_this.signObj.isOpenOcr && _this.signObj.ocrObj) {
        //   ocrCapture = new window.OCRCapture()
        //   ocrCapture.text = _this.signObj.ocrObj.text
        //   ocrCapture.IPAdress = _this.signObj.ocrObj.IPAdress
        //   ocrCapture.appID = _this.signObj.ocrObj.appID
        //   ocrCapture.count = _this.signObj.ocrObj.count
        //   ocrCapture.language = _this.signObj.ocrObj.language || window.Language.CHS
        //   ocrCapture.resolution = _this.signObj.ocrObj.resolution
        //   ocrCapture.serviceID = _this.signObj.ocrObj.serviceID
        // }
        signatureConfig.ocrCapture = _this.ocrCapture
        let res = _this.apiInstance.addSignatureObj(context_id, signatureConfig)
        if (res) {
          console.log('注册签名框成功')
          return res
        } else {
          console.log('注册签名框失败')
          return res
        }
      },
      addCommentObj(context_id) {
        let _this = this
        if (!_this.commentsObj.signName || !_this.commentsObj.signIdNo) {
          return false
        }
        let signer = new window.Signer(_this.commentsObj.signName, _this.commentsObj.signIdNo)
        let signerRule = null
        if (_this.commentsObj && _this.commentsObj.signLocaType == '1' && _this.commentsObj.signRuleKeyWord) {
          //关键字定位
          signerRule = new window.SignRule_KeyWordV2(_this.commentsObj.signRuleKeyWord.keyword,
            _this.commentsObj.signRuleKeyWord.xOffset,
            _this.commentsObj.signRuleKeyWord.yOffset,
            _this.commentsObj.signRuleKeyWord.pageNo,
            _this.commentsObj.signRuleKeyWord.KWIndex)
        } else if (_this.commentsObj && _this.commentsObj.signLocaType == '2' && _this.commentsObj.signRuleXYZ) {
          //坐标定位
          signerRule = new window.SignRule_XYZ(_this.commentsObj.signRuleXYZ.left,
            _this.commentsObj.signRuleXYZ.top,
            _this.commentsObj.signRuleXYZ.right,
            _this.commentsObj.signRuleXYZ.bottom,
            _this.commentsObj.signRuleXYZ.pageNo,
            _this.commentsObj.signRuleXYZ.unit)
        } else {
          return Toast.info('缺少定位参数', 1000)
        }
        let commentConfig = new window.CommentConfig(signer, signerRule)
        if (!_this.commentsObj.commentConfig) {
          return Toast.info('缺少批注配置信息', 1000)
        }
        commentConfig.cid = _this.commentsObj.commentConfig.cid
        commentConfig.commitment = _this.commentsObj.commentConfig.commitment
        commentConfig.mass_words_in_single_line = _this.commentsObj.commentConfig.mass_words_in_single_line
        commentConfig.mass_word_height = _this.commentsObj.commentConfig.mass_word_height
        commentConfig.mass_word_width = _this.commentsObj.commentConfig.mass_word_width
        commentConfig.penColor = _this.commentsObj.commentConfig.penColor
        commentConfig.comment_stroke_width = _this.commentsObj.commentConfig.comment_stroke_width
        commentConfig.nessesary = _this.commentsObj.commentConfig.nessesary
        commentConfig.commentImgRatio = _this.commentsObj.commentConfig.commentImgRatio
        commentConfig.comment_max_times = _this.commentsObj.commentConfig.comment_max_times
        commentConfig.isdistinguish = _this.commentsObj.commentConfig.isdistinguish
        // let ocrCapture = null
        // if (_this.commentsObj.isOpenOcr && _this.commentsObj.ocrObj) {
        //   ocrCapture = new window.OCRCapture()
        //   ocrCapture.text = _this.commentsObj.ocrObj.text
        //   ocrCapture.IPAdress = _this.commentsObj.ocrObj.IPAdress
        //   ocrCapture.appID = _this.commentsObj.ocrObj.appID
        //   ocrCapture.count = _this.commentsObj.ocrObj.count
        //   ocrCapture.language = _this.commentsObj.ocrObj.language || window.Language.CHS
        //   ocrCapture.resolution = _this.commentsObj.ocrObj.resolution
        //   ocrCapture.serviceID = _this.commentsObj.ocrObj.serviceID
        // }
        commentConfig.ocrCapture = _this.ocrCapture
        let res = _this.apiInstance.addCommentObj(context_id, commentConfig)
        if (res) {
          console.log('注册批注框成功')
          return res
        } else {
          console.log('注册批注框失败')
          return res
        }
      },
      signDialog(context_id = 20) {
        let _this = this
        if (!_this.apiInstance) {
          console.log('信手书接口没有初始化1',)
          _this.initSign()
        }
        if (context_id == 20) {
          switch (_this.apiInstance.showSignatureDialog(context_id)) {
            case _this.apiInstance.RESULT_OK:
              _this.isPopupShow = true
              break
            case _this.apiInstance.EC_API_NOT_INITED:
              console.log('信手书接口没有初始化')
              break
            case _this.apiInstance.EC_WRONG_CONTEXT_ID:
              break
          }
        } else if (context_id == 21) {
          switch (_this.apiInstance.showSingleSignDialog(context_id)) {
            case _this.apiInstance.RESULT_OK:
              _this.isPopupShow = true
              window.getSignImg = _this.checkSignImg
              break
            case _this.apiInstance.EC_API_NOT_INITED:
              console.log('信手书接口没有初始化')
              break
            case _this.apiInstance.EC_WRONG_CONTEXT_ID:
              console.log('没有配置相应context_id的签字对象')
              break
          }
        }
      },
      commentDialog(context_id = 30) {
        let _this = this
        if (!_this.apiInstance) {
          console.log('信手书接口没有初始化')
          _this.initSign()
        }
        switch (_this.apiInstance.showCommentDialog(context_id)) {
          case 0:
            _this.isPopupShow = true
            window.getCommentImg = _this.checkCommentImg
            break
          case 1:
            console.log('信手书接口没有初始化')
            break
          case 2:
            console.log('没有配置相应context_id的签字对象')
            break
          case 5:
            console.log('批注签名框已弹出，请勿重复操作！')
        }
      },
      checkSignImg(imgData, text) {
        console.log(imgData, text, 'checkSignImg')
        if (!this.signObj.isOpenOcr) {
          return new Promise(resolve => {
            this.$emit('signCallBack', {
              img: imgData,
              text
            })
            resolve(true)
          })
        }
        Toast.loading('识别中')
        return this.ocr({
          iPAdress: this.signObj.ocrObj.iPAdress,
          businessNo: this.signObj.ocrObj.businessNo,
          businessType: this.signObj.ocrObj.businessType,
          imageBase64: imgData,
          systemType: this.signObj.ocrObj.systemType,
          text
        }).then(res => {
          if (res && res.resultCode == '1') {
            if (res.result == 'CONSISTENCY') {
              Toast.hide()
              this.$emit('signCallBack', {
                img: imgData,
                text
              })
              return true
            } else {
              setTimeout(() => {
                Toast.hide()
                setTimeout(() => {
                  Toast.info('识别失败', 1000)
                }, 200)
              }, 10)
              return false
            }
          } else {
            Toast.info(res.failDesc || '识别失败', 1000)
            return false
          }
        })
      },
      checkCommentImg(imgData, text) {
        console.log(imgData, text, 'checkCommentImg',this.commentsObj.commentConfig.commitment)
        this.baseImges1.push(imgData)
        if(this.baseImges1.length == this.commentsObj.commentConfig.commitment.length) {
          this.drawCanvas(this.baseImges1)
        }
        if (!this.commentsObj.isOpenOcr) {
          return new Promise(resolve => {
            this.$emit('signCallBack', {
              img: imgData,
              text
            })
            resolve(true)
          })
        }
        Toast.loading('识别中')
        return this.ocr({
          iPAdress: this.commentsObj.ocrObj.iPAdress,
          businessNo: this.commentsObj.ocrObj.businessNo,
          businessType: this.commentsObj.ocrObj.businessType,
          imageBase64: imgData,
          systemType: this.commentsObj.ocrObj.systemType,
          text
        }).then(res => {
          if (res && res.resultCode == '1') {
            if (res.result == 'CONSISTENCY') {
              Toast.hide()
              this.$emit('signCallBack', {
                img: imgData,
                text
              })
              return true
            } else {
              setTimeout(() => {
                Toast.hide()
                setTimeout(() => {
                  Toast.info('识别失败', 1000)
                }, 200)
              }, 10)
              return false
            }
          } else {
            Toast.info(res.failDesc || '识别失败', 1000)
            return false
          }
        })
      },
      signBack() {
        this.$emit('signBack')
      },
      // 回退
      commentBack() {
        if(this.baseImges1 && this.baseImges1.length > 0) {
          this.baseImges1.pop()
        }
        this.$emit('commentBack')
      },
      //单字签名取消
      cancelSign() {
        this.$emit('cancelSign')
        this.isPopupShow = false
        window.cancelSign()
      },
      //批注签名取消
      commentCancel() {
        console.log('取消')
        this.$emit('cancelComment')
        this.isPopupShow = false
      },
      signSubmit() {
        // Toast.info('加载中')
        window.sign_confirm()
      },
      async ocr({
        iPAdress,
        businessNo,
        businessType,
        imageBase64,
        systemType,
        text
      }) {
        imageBase64 = await this.imgBgColor(imageBase64)
        let res = http.post(iPAdress, {
          businessNo,
          businessType,
          systemType,
          imageType: 'HANDWRITE',
          imageBase64,
          imageFormat: 'jpg',
          isVerifyCont: '1',
          verifyInfo: JSON.stringify({
            content: text
          })
        })
        return res
      },
      drawCanvas(imgsrcArray){
        var _this = this
        var canvas = document.createElement('canvas')
        var ctx = canvas.getContext('2d')
        var images = new window.Image()
        images.src = imgsrcArray[0]
        canvas.width = images.width * imgsrcArray.length
        canvas.height = images.height
        ctx.fillStyle = '#ffffff'
        ctx.fillRect(0, 0, canvas.width, canvas.height)
        var imglen = imgsrcArray.length
        var drawimg = (function f(n){
          if(n < imglen){
            var img = new Image()
            img.onload = function(){
              ctx.drawImage(img,img.width * n,0)
              f(n+1)
            }
            img.src = imgsrcArray[n]
          } else {
            _this.$emit('againImg',canvas.toDataURL("image/jpeg"))
          }
        })(0)
      },
      async imgBgColor(datrUrl, bgColor = '#ffffff') {
        let canvas = document.createElement('canvas')
        let context = canvas.getContext('2d')
        let img = new window.Image()
        img.src = datrUrl
        return await new Promise(resolve => {
          img.onload = function () {
            canvas.width = img.width
            canvas.height = img.height
            // 在canvas绘制前填充白色背景
            context.fillStyle = bgColor
            context.fillRect(0, 0, canvas.width, canvas.height)
            context.drawImage(img, 0, 0)
            resolve(canvas.toDataURL('image/jpeg'))
          }
        })

      },
      getSignInfo() {
        let _this = this
        console.log(_this.apiInstance.isReadyToUpload())
        if (_this.apiInstance.isReadyToUpload()) {
          let sign = _this.apiInstance.getUploadDataGram()
          _this.signInfo.signData = sign
          // _this.$emit('getSignInfo', _this.signInfo)
          return _this.signInfo
        }
      }
    }
  }
</script>
<style lang="less" scoped>
  .anySignMiniCore {
    .dialog {
      // position: absolute;
      // top: 0px;
      // left: 0px;
      width: 100%;
      z-index: 9999;
      background-color: #ffffff;
    }

    .comment_titlecss {
      font-size: 20px;
      clear: both;
    }

    /deep/.md-popup {
      .md-popup-box {
        background-color: #ffffff;
        height: 100%;
      }
    }

    .comment_btncontainer {
      text-align: center;
      margin: 0 auto;
      font-size: 20px;
      width: 100%;
      clear: both;
      // position: absolute;
      // bottom: 10;
    }

    .signImagecss {
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
      overflow: scroll;
      border: 1px solid rgb(229, 229, 229)
    }

    #tmpcanvascss {
      border: 1px solid rgb(229, 229, 229);
      position: relative;

      #signTitle {
        float: none !important;
      }

      #comment_canvas {
        position: absolute !important;
        top: 0 !important;
        left: 0 !important;
      }
    }

    #single_tmpcanvascss {
      position: relative;

      #single_signTitle {
        width: 100% !important;
        background-size: 100% 100%;
        color: rgb(229, 229, 229);
      }

      #single_anysignCanvas {
        position: absolute;
        top: 0;
        left: 0;
      }
    }

    #btnContainerInner {
      text-align: center;
      margin: 0 auto;
      font-size: 20px;
      width: 100%;
      clear: both;
      // position: absolute;
    }

    #signTitle {
      width: 100%;
    }

    #anysign_title {
      width: 100%;
      color: #333333;
    }

    #container {
      border: 1px solid #dddddd;
    }

    .btn_orange {
      font-size: 20pt;
      color: #fef4e9;
      border: solid 1px #da7c0c;
      background: #f78d1d;
      background: -webkit-gradient(linear, left top, left bottom, from(#faa51a), to(#f47a20));
    }
  }
</style>